package com.example.online_forum.controller;

import com.example.online_forum.common.AppResult;
import com.example.online_forum.common.ResultCode;
import com.example.online_forum.config.AppConfig;
import com.example.online_forum.model.User;
import com.example.online_forum.services.IUserService;
import com.example.online_forum.untils.MD5Util;
import com.example.online_forum.untils.StringUtil;
import com.example.online_forum.untils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Api(tags = "用户接口")
//日志注释
@Slf4j
@RestController
//路由映射
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    /**
     *
     * @param username
     * @param nickname
     * @param password
     * @param passwordRepeat
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping ("/register")
    //@NonNull 参数效验非空校验
    //@ApiParam 对参数的描述
    //@RequestParam 前后端交互中的key
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("用户昵称") @RequestParam("nickname")@NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password")@NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat")@NonNull String passwordRepeat){
        //参数效验
//        if(StringUtil.isEmpty(username)||StringUtil.isEmpty(nickname)
//        ||StringUtil.isEmpty(password)||StringUtil.isEmpty(passwordRepeat)){
//            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
//        }
        if(!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //生成盐值
        String salt = UUIDUtil.UUID_32();
        //生成密码密文
        String pw = MD5Util.md5Salt(password,salt);
        //设置密码
        user.setSalt(salt);
        user.setPassword(pw);

        userService.createNormalUser(user);
        return AppResult.success();
    }
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password){
        //查询是否有对象存在
        User user = userService.login(username,password);
        if(user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //登录成功就把user对象设置到session中
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        //返回结果
        return AppResult.success();
    }
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User>  getUserInfo(HttpServletRequest request,//required = false 非必传项
                                  @ApiParam("用户id") @RequestParam(value = "id",required = false) Long id){

        User user = null;
        //根据id的值来获取user对象
        if(id == null){
            HttpSession session = request.getSession(false);
            //session是否存在和用户信息是否有效
//            if(session == null || session.getAttribute(AppConfig.USER_SESSION) == null){
//                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
//            }
            //存在则获取session中登录的用户信息
            user = (User) session.getAttribute(AppConfig.USER_SESSION);

        }else {
            user = userService.selectById(id);
        }
        if(user == null){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }
    @ApiOperation("用户注销")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        //获取session对象
        HttpSession session = request.getSession(false);
        //判断session对象是否有效
        if(session != null){
            log.info("登录状态下退出成功");
            //用户在登录状态,直接销毁session
            session.invalidate();
        }
        return  AppResult.success("退出成功");
    }

    /**
     * 修改个人信息
     * @param username 用户名
     * @param nickname 昵称
     * @param gender 性别
     * @param email 邮箱
     * @param phoneNum 电话号
     * @param remark 个人简介
     * @return AppResult
     */

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo (HttpServletRequest request,
                                 @ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
                                 @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                 @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                 @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                 @ApiParam("电话号") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                 @ApiParam("个人简介") @RequestParam(value = "remark",required = false) String remark) {
        // 1. 接收参数
        // 2. 对参数做非空校验（全部都为空，则返回错误描述）
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark) && gender == null) {
            // 返回错误信息
            return AppResult.failed("请输入要修改的内容");
        }

        // 从session中获取用户Id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 3. 封装对象
        User updateUser = new User();
        updateUser.setId(user.getId()); // 用户Id
        updateUser.setUsername(username); // 用户名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setEmail(email); // 邮箱
        updateUser.setPhoneNum(phoneNum); // 电话
        updateUser.setRemark(remark); // 个人简介

        // 4. 调用Service中的方法
        userService.modifyInfo(updateUser);
        // 5. 查询最新的用户信息
        user = userService.selectById(user.getId());
        // 6. 把最新的用户信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION, user);
        // 7. 返回结果
        return AppResult.success(user);
    }
    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword (HttpServletRequest request,
                                     @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                     @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                     @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        // 1. 校验新密码与确认密码是否相同
        if (!newPassword.equals(passwordRepeat)) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 2. 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 3. 调用Service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        // 4. 销毁session
        if (session != null) {
            session.invalidate();
        }
        // 5. 返回结果
        return AppResult.success();
    }


}
